package com.jsaas.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jsaas.utils.Exceptions;
import com.jsaas.utils.MyUtils;

/**   
* @Title: ExceptionInterceptor.java 
* @Package com.xhc.interceptor 
* @Description: TODO(全局异常拦截器) 
* @author tuozq 
* @date 2017年10月18日 下午4:57:41 
* @version V1.0   
*/
public class ExceptionInterceptor implements Interceptor {

	public void intercept(Invocation ai) {
		Controller controller = ai.getController();
		HttpServletRequest request = controller.getRequest();
		boolean successed = false;
		String exception = "";
		try {
			ai.invoke();
			successed = true;
		} catch (Exception e) {
			e.printStackTrace();
			successed = false;
			// 判断是否ajax请求
			boolean isAjax = MyUtils.isAjax(request);
			String msg = e.getMessage();
			exception = Exceptions.getStackTraceAsString(e);
			if (isAjax) {
				controller.renderJson(Ret.fail().set("msg", "服务器发生异常，请联系管理员！").set("stack", exception).set("source", "ExceptionInterceptor"));
			} else {
				String redirctUrl = request.getHeader("referer");
				if (StringUtils.isBlank(redirctUrl)) {
					redirctUrl = request.getRequestURI();
				}
				controller.setAttr("msg", msg);
				controller.setAttr("stack", exception);
				controller.setAttr("redirctUrl", redirctUrl);
				controller.render("/views/error/500.html");
			}
		} finally {

		}
		return;

	}

}
